package com.abu.ossms.template;

import com.abu.ossms.properties.OssProperties;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OssTemplate {

    @Autowired
    private OssProperties ossProperties;

    public String upload(MultipartFile file) {
        String returnUrl = null;
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = this.ossProperties.getEndpoint();
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = this.ossProperties.getAccessKeyId();
        String accessKeySecret = this.ossProperties.getAccessKeySecret();
        String bucketName = this.ossProperties.getBucketName();
//        图片名称
        String now = DateTime.now().toString("yyyy-MM-dd");
        String replaceUUID = UUID.randomUUID().toString().replace("-", "");
        String filename = replaceUUID + "·" + file.getOriginalFilename();
        String newFileName = now + "/" + filename;

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ossClient.putObject(bucketName, newFileName, inputStream);

// 关闭OSSClient。
//        https://mall-kk.oss-cn-beijing.aliyuncs.com/dog.jpg
        returnUrl = "https://" + bucketName + "." + endpoint + "/" + newFileName + "";
        ossClient.shutdown();
        return returnUrl;
    }
}
